package hu.jonas.allunit.handlers;

import hu.jonas.allunit.nature.AllUnitNature;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.handlers.HandlerUtil;

public class RemoveAllUnitNatureHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		ISelection selection = HandlerUtil.getActiveMenuSelection(event);
		
		if (selection instanceof TreeSelection) {
			TreeSelection treeSelection = (TreeSelection) selection;
			
			TreePath[] paths = treeSelection.getPaths();
			if (paths.length > 0) {
				Object firstSegment = paths[0].getFirstSegment();
				
				if (firstSegment instanceof IJavaProject) {
					IJavaProject javaProject = (IJavaProject) firstSegment;
					
					try {
						IProject project = javaProject.getProject();
						IProjectDescription description = project.getDescription();
						String[] natureIds = description.getNatureIds();
						List<String> newNatureIds = new ArrayList<String>(Arrays.asList(natureIds));
						
						newNatureIds.remove(AllUnitNature.ID);
						
						description.setNatureIds(newNatureIds.toArray(new String[0]));
						project.setDescription(description, null);
						
					} catch (CoreException e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return null;
	}

}
